package phone

import (
	"encoding/json"
	"hft/global"
	"hft/tools"
	"hft/tools/phone/model"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type Phone400 struct{}

// 获取secret
func (p *Phone400) getSecret(params *url.Values, pwd string) string {

	return tools.Md5(strings.ReplaceAll(strings.ReplaceAll(params.Encode(), "=", ""), "&", "") + pwd)
}

// 基础请求
func (p *Phone400) baseRequest(path string, params *url.Values) (data []byte, err error) {
	request, err := url.Parse(global.OC_CONFIG.Phone.Url + path)

	if err != nil {
		return nil, err
	}

	resp, err := http.NewRequest("POST", request.String(), strings.NewReader(params.Encode()))

	if err != nil {
		return nil, err
	}

	resp.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")

	client := &http.Client{}
	result, err := client.Do(resp)

	if err != nil {
		return nil, err
	}

	defer result.Body.Close()

	resBody, err := ioutil.ReadAll(result.Body)

	if err != nil {
		return nil, err
	}

	return resBody, nil
}

// 获取token
func (p *Phone400) GetToken() (token string, err error) {
	var newParams = url.Values{
		"user":      []string{global.OC_CONFIG.Phone.User},
		"appver":    []string{global.OC_CONFIG.Phone.Appver},
		"timestamp": []string{tools.GetCurrentTimestamp()},
	}

	var secret = p.getSecret(&newParams, global.OC_CONFIG.Phone.Password)

	newParams.Add("secret", secret)

	data, err := p.baseRequest("/union400Login.action", &newParams)

	if err != nil {
		return "", err
	}

	var tokenRes *model.Token

	err = json.Unmarshal(data, &tokenRes)

	if err != nil {
		return "", nil
	}

	_, err = global.OC_REDIS.Set(tools.Md5("phone_token"), tokenRes.Data.Token, 23*time.Hour).Result() //设置token过去时间

	if err != nil {
		return "", err
	}

	return tokenRes.Data.Token, nil
}

// 实际封装api
func (p *Phone400) BaseRequestV2(path string, params *url.Values) (resBody []byte) {
	// 添加参数
	params.Add("user", global.OC_CONFIG.Phone.User)
	params.Add("appver", global.OC_CONFIG.Phone.Appver)
	params.Add("timestamp", tools.GetCurrentTimestamp())

	var newPwd string

	oldToken, err := global.OC_REDIS.Get(tools.Md5("phone_token")).Result()
	// 获取token
	if err != nil {
		newPwd, _ = p.GetToken()
	} else {
		newPwd = oldToken
	}
	// 添加企业号码
	params.Add("account", global.OC_CONFIG.Phone.Account)
	// 获取secret
	var secret = p.getSecret(params, newPwd)
	params.Add("secret", secret) //添加新计算的secret
	// 发送请求
	data, err := p.baseRequest(path, params)

	return data

}

//

var Phone400Api = new(Phone400)
